//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.client.game.left;

import tv.dyndns.kishibe.client.Constant;
import tv.dyndns.kishibe.client.Sanitize;
import tv.dyndns.kishibe.client.game.WidgetInputClick;
import tv.dyndns.kishibe.client.game.click.MarkedCanvas;
import tv.dyndns.kishibe.client.geom.Point;
import tv.dyndns.kishibe.client.packet.PacketProblemData;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;

public class WidgetPlayer extends HorizontalPanel {
	private final HTML htmlName = new HTML();
	private String myAnswer;
	protected PacketProblemData problem;
	private boolean flagRecieved = false;
	private boolean flagOpen = false;
	private boolean flagTimeUp = false;
	private final WidgetPlayerList parent;
	private boolean isCorrect;
	private int currentX;
	private int currentY;
	private int destX;
	private int destY;
	private static final double INTERPOLATE_RATIO = 0.1;
	private final AnswerPopupFactory answerPopupFactory;
	private AnswerPopup answerPopup = null;

	public WidgetPlayer(String name, String imageFileName, WidgetPlayerList parent, int x, int y) {
		destX = this.currentX = x;
		destY = this.currentY = y;
		this.parent = parent;
		answerPopupFactory = new AnswerPopupFactory(parent);

		setPixelSize(180, 50);
		setVerticalAlignment(ALIGN_MIDDLE);

		final Image image = new Image(Constant.ICON_URL_PREFIX + imageFileName);
		image.setPixelSize(Constant.ICON_SIZE, Constant.ICON_SIZE);
		add(image);
		setCellWidth(image, "50px");

		setPlayerName(name);
		htmlName.addStyleDependentName("playerName");
		add(htmlName);

		update();
	}

	public void setProblem(PacketProblemData problem) {
		this.problem = problem;
		answerPopup = answerPopupFactory.get(problem);
		answerPopup.setPosition(currentX, currentY);
	}

	public void setPlayerName(String name) {
		if (name.indexOf(Constant.DELEMITER_PLAYER_NAME) != -1) {
			name = name.substring(0, name.lastIndexOf(Constant.DELEMITER_PLAYER_NAME));
		}
		name = Sanitize.getInstance().html(name);
		name = name.replaceFirst(" ", "<br>");
		htmlName.setHTML(name);
	}

	public void recieveAnswer(String answer) {
		if (answer.equals("")) {
			answer = AnswerPopup.LABEL_NO_ANSWER;
		}
		myAnswer = answer;

		flagRecieved = true;

		update();
	}

	public void open() {
		flagOpen = true;

		update();
	}

	public void recieveTimeUp() {
		flagTimeUp = true;

		update();
	}

	public void clearAnswer() {
		flagRecieved = false;
		flagOpen = false;
		flagTimeUp = false;
		myAnswer = "";

		if (answerPopup != null) {
			answerPopup.hide();
		}

		markSegmentId = MarkedCanvas.REGISTER;
		markPointerId = MarkedCanvas.REGISTER;
		markYesId = MarkedCanvas.REGISTER;
		markNoId = MarkedCanvas.REGISTER;

		update();
	}

	public void update() {
		if (!isUpdating) {
			DeferredCommand.addCommand(commandUpdate);
		}
	}

	private boolean isUpdating = false;
	private final Command commandUpdate = new Command() {
		public void execute() {
			updateHelper();
			isUpdating = false;
		}
	};

	private void updateHelper() {
		if (flagTimeUp) {
			isCorrect = flagRecieved && problem.isCorrect(myAnswer);

			if (answerPopup == null) {
				return;
			}

			if (isCorrect) {
				answerPopup.setBackgroundColor(AnswerPopup.COLOR_CORRECT);
			} else {
				answerPopup.setBackgroundColor(AnswerPopup.COLOR_WRONG);
			}

			if (flagRecieved) {
				answerPopup.show(myAnswer);
			} else {
				answerPopup.show(AnswerPopup.LABEL_TIME_UP);
			}

		} else {
			if (answerPopup == null) {
				return;
			}

			if (flagRecieved) {
				answerPopup.setBackgroundColor(AnswerPopup.COLOR_ANSWERED);
				if (flagOpen) {
					answerPopup.show(myAnswer);
				} else {
					answerPopup.show(AnswerPopup.LABEL_ANSWERED);
				}

			} else {
				answerPopup.hide();
			}
		}

		if (problem.type == Constant.TYPE_CLICK) {
			updateClick();
		}
	}

	public boolean getIsCorrect() {
		return isCorrect;
	}

	public boolean isAnswerRecieved() {
		return flagRecieved;
	}

	public int getCurrentX() {
		return currentX;
	}

	public int getCurrentY() {
		return currentY;
	}

	public void setDestX(int x) {
		this.destX = x;
	}

	public void setDestY(int y) {
		this.destY = y;
	}

	public void updatePosition() {
		final int newX = (int) ((double) currentX * (1.0 - INTERPOLATE_RATIO) + (double) destX * INTERPOLATE_RATIO);
		final int newY = (int) ((double) currentY * (1.0 - INTERPOLATE_RATIO) + (double) destY * INTERPOLATE_RATIO);

		if (newX != currentX || newY != currentY) {
			currentX = newX;
			currentY = newY;
			parent.setWidgetPosition(this, currentX, currentY);
			answerPopup.setPosition(currentX, currentY);
		}

		if (problem != null && problem.type == Constant.TYPE_CLICK) {
			updatePositionClilck();
		}
	}

	// 以下画像クリッククイズのための特殊処理
	private int markSegmentId = MarkedCanvas.REGISTER;
	private int markPointerId = MarkedCanvas.REGISTER;
	private int markYesId = MarkedCanvas.REGISTER;
	private int markNoId = MarkedCanvas.REGISTER;

	private void updateClick() {
		final MarkedCanvas canvas = getCanvas();
		if (canvas == null || !flagRecieved) {
			return;
		}

		final Point answerPosition = getAnswerPosition();
		if (!answerPosition.isValid()) {
			return;
		}

		final int x = answerPosition.x;
		final int y = answerPosition.y;

		if (flagTimeUp) {
			if (problem.isCorrect(myAnswer)) {
				// 正解
				canvas.removeMark(markPointerId);
				markYesId = canvas.addYesMark(x, y, markYesId);
			} else {
				canvas.removeMark(markPointerId);
				markNoId = canvas.addNoMark(x, y, markNoId);
			}
		} else if (flagOpen) {
			markPointerId = canvas.addPointerMark(x, y, markPointerId);
		}
	}

	private void updatePositionClilck() {
		final MarkedCanvas canvas = getCanvas();
		if (canvas == null || !flagRecieved || !flagOpen) {
			return;
		}

		final int[] segmentBeginPosition = getSegmentBeginPosition();
		final Point answerPosition = getAnswerPosition();
		if (answerPosition == null || !answerPosition.isValid()) {
			return;
		}

		final int startX = segmentBeginPosition[0] - WidgetInputClick.getInstance().getImageOffset()[0];
		final int startY = segmentBeginPosition[1] - WidgetInputClick.getInstance().getImageOffset()[1];
		final int endX = answerPosition.x;
		final int endY = answerPosition.y;
		markSegmentId = canvas.addSegmentMark(startX, startY, endX, endY, markSegmentId);
	}

	private MarkedCanvas getCanvas() {
		final WidgetInputClick widgetInputClick = WidgetInputClick.getInstance();
		if (widgetInputClick == null) {
			return null;
		}

		return widgetInputClick.getMarkedCanvas();
	}

	private int[] getSegmentBeginPosition() {
		final int x = getAbsoluteLeft() + getOffsetWidth() / 2;
		final int y = getAbsoluteTop() + getOffsetHeight() / 2;
		return new int[] { x, y };
	}

	private Point getAnswerPosition() {
		if (myAnswer == null) {
			return null;
		}

		return new Point(myAnswer);
	}

	public String getMyAnswer() {
		return myAnswer;
	}
}
